package com.jkoss.wine.investment.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jkoss.base.controller.BaseController;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.util.Constant;
import com.jkoss.common.vo.DwzPageBean;
import com.jkoss.wine.config.mvc.MoneyExcelHandler;
import com.jkoss.wine.investment.entity.Handover;
import com.jkoss.wine.investment.entity.Investment;
import com.jkoss.wine.investment.service.IHandoverService;
import com.jkoss.wine.investment.service.IInvestmentFollowService;
import com.jkoss.wine.investment.service.IInvestmentService;
import com.jkoss.wine.investment.vo.HandoverVo;
import com.jkoss.wine.system.entity.Areas;
import com.jkoss.wine.system.service.IAreasService;
import com.jkoss.wine.system.service.IMerchantEmployeesService;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;

/**
 * 新客户基本情况交接表 前端控制器
 * 
 * @Author Jason
 * @Version 1.0, 2018-11-25
 * @See
 * @Since com.jkoss.wine.investment.controller
 * @Description: TODO
 */
@Controller
@RequestMapping("/investment/handover")
public class HandoverController extends BaseController {

	@Autowired
	private IAreasService iAreasService;

	@Autowired
	private IHandoverService iHandoverService;

	@Autowired
	private IMerchantEmployeesService iMerchantEmployeesService;
	@Autowired
	private IInvestmentService iInvestmentService;
	@Autowired
	private IInvestmentFollowService iInvestmentFollowService;

	@RequestMapping("/list")
	@RequiresPermissions("/investment/handover/list")
	public String list(DwzPageBean dwzPageBean, String name, String phone, String areaCode, String state, String startTime, String endTime, String source, String stle, String ctno, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		dwzPageBean.getCountResultMap().put("name", name);
		dwzPageBean.getCountResultMap().put("phone", phone);
		dwzPageBean.getCountResultMap().put("startTime", startTime);
		dwzPageBean.getCountResultMap().put("endTime", endTime);

		dwzPageBean.getCountResultMap().put("source", source);
		dwzPageBean.getCountResultMap().put("stle", stle);
		dwzPageBean.getCountResultMap().put("ctno", ctno);

		if (!CommonUtil.isBlank(state)) {
			dwzPageBean.getCountResultMap().put("state", state);
		}
		// 省市级查询
		Wrapper wrapper1 = Condition.create().like("id", "0000");
		List<Areas> provinces = iAreasService.selectList(wrapper1);
		map.put("provinces", provinces);
		String repAreaCode = "";
		if (!CommonUtil.isBlank(areaCode)) {
			String[] areas = areaCode.split(",");
			for (int i = 0; i < areas.length; i++) {
				repAreaCode += areas[i];
				if (i != 2 && areas.length - 1 > i && !CommonUtil.isBlank(areas[i + 1])) {
					repAreaCode += ",";
				}
			}
			if (areas.length >= 1 && !CommonUtil.isBlank(areas[0])) {
				dwzPageBean.getCountResultMap().put("province", areas[0]);
				if (areas.length >= 2 && !CommonUtil.isBlank(areas[0])) {
					dwzPageBean.getCountResultMap().put("city", areas[1]);
				}
				// 市
				String city = areas[0].substring(0, 2);
				Wrapper cityWrapper = Condition.create().andNew("id like '" + city + "%00'").ne("id", city + "0000");
				List<Areas> citys = iAreasService.selectList(cityWrapper);
				map.put("citys", citys);
			}
			if (areas.length >= 2 && !CommonUtil.isBlank(areas[1])) {
				if (areas.length >= 3 && !CommonUtil.isBlank(areas[0])) {
					dwzPageBean.getCountResultMap().put("county", areas[2]);
				}
				// 区
				String county = areas[1].substring(0, 4);
				Wrapper countyWrapper = Condition.create().andNew("id like '" + county + "%'").ne("id", county + "00");
				List<Areas> countys = iAreasService.selectList(countyWrapper);
				map.put("countys", countys);
			}
		}
		Wrapper wrapper = Condition.create().ne("h.del", 1).like("h.name", name).like("h.phone", phone);
		if (!CommonUtil.isBlank(state)) {
			wrapper.eq("h.state", state);
		}
		if (!CommonUtil.isBlank(startTime)) {
			wrapper.ge("h.sgtm", startTime);
		}
		if (!CommonUtil.isBlank(endTime)) {
			wrapper.le("h.sgtm", CommonUtil.dateLastTime(endTime));
		}

		if (!CommonUtil.isBlank(source)) {
			wrapper.like("h.source", source);
		}
		if (!CommonUtil.isBlank(stle)) {
			wrapper.like("h.stle", stle);
		}
		if (!CommonUtil.isBlank(ctno)) {
			wrapper.like("h.ctno", ctno);
		}

		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("add_time", false);
		}
		Page resultPage = iHandoverService.selectVoPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "investment/handover/list";
	}

	@RequestMapping("/toInsert")
	@RequiresPermissions("/investment/handover/toInsert")
	public String toInsert(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		// 地区省份
		Wrapper wrapper = Condition.create().like("id", "0000");
		List<Areas> provinces = iAreasService.selectList(wrapper);
		map.put("provinces", provinces);

		List imidlist = iMerchantEmployeesService.selectEmployeesByRole("招商经理");
		List opidlist = iMerchantEmployeesService.selectEmployeesByRole("运营督导");
		List rgidlist = iMerchantEmployeesService.selectEmployeesByRole("区域经理");

		map.put("imidlist", imidlist);
		map.put("opidlist", opidlist);
		map.put("rgidlist", rgidlist);

		// 招商信息
		Wrapper investmentsWrapper = Condition.create().ne("del", 1).orderBy("phone", true);
		List<Investment> investments = iInvestmentService.selectList(investmentsWrapper);
		map.put("investments", investments);
		return "investment/handover/edit";
	}

	@RequestMapping("/insert")
	@RequiresPermissions("/investment/handover/toInsert")
	@ResponseBody
	public Object insert(@Valid Handover handover, MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {

		if (!CommonUtil.isBlank(file) && !CommonUtil.isBlank(file.getOriginalFilename())) {
			File filePath = new File(Constant.IMAGES_PATH);
			if (!filePath.exists()) {
				filePath.mkdirs();
			}
			file.transferTo(new File(Constant.IMAGES_PATH + file.getOriginalFilename()));
			handover.setAnex(Constant.IMAGES_URL + "/" + file.getOriginalFilename());
		}
		// 当前操作人
		handover.setOperator(getUserId());
		// 添加时间
		handover.setAddTime(CommonUtil.getDate());
		// 是否删除 0-未删除 1-已删除
		handover.setDel(0);
		// 状态：1-申请移交、2-移交通过、3-移交不通过
		handover.setState(1);
		if (iHandoverService.insert(handover)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	@RequestMapping("/toUpdate")
	@RequiresPermissions("/investment/handover/toUpdate")
	public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {

		Handover handover = iHandoverService.selectById(id);
		String string = handover.getAreaCode();
		String[] strings = string.split(",");
		String province = strings[0];
		// 省
		Wrapper wrapper = Condition.create().like("id", "0000");
		List<Areas> provinces = iAreasService.selectList(wrapper);
		map.put("provinces", provinces);
		map.put("province", province);
		// 市
		String city = province.substring(0, 2);
		Wrapper cityWrapper = Condition.create().andNew("id like '" + city + "%00'").ne("id", city + "0000");
		List<Areas> citys = iAreasService.selectList(cityWrapper);
		map.put("citys", citys);
		map.put("city", strings[1]);
		// 区
		String county = strings[1].substring(0, 4);
		Wrapper countyWrapper = Condition.create().andNew("id like '" + county + "%'");
		List<Areas> countys = iAreasService.selectList(countyWrapper);
		map.put("countys", countys);
		map.put("county", strings[2]);

		List imidlist = iMerchantEmployeesService.selectEmployeesByRole("招商经理");
		List opidlist = iMerchantEmployeesService.selectEmployeesByRole("运营督导");
		List rgidlist = iMerchantEmployeesService.selectEmployeesByRole("区域经理");

		map.put("imidlist", imidlist);
		map.put("opidlist", opidlist);
		map.put("rgidlist", rgidlist);
		// 招商信息
		Wrapper investmentsWrapper = Condition.create().ne("del", 1);
		List<Investment> investments = iInvestmentService.selectList(investmentsWrapper);
		map.put("investments", investments);
		map.put("record", handover);
		return "investment/handover/edit";
	}

	@RequestMapping("/update")
	@RequiresPermissions("/investment/handover/toUpdate")
	@ResponseBody
	public Object update(@Valid Handover handover, MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
		if (!CommonUtil.isBlank(file) && !CommonUtil.isBlank(file.getOriginalFilename())) {
			File filePath = new File(Constant.IMAGES_PATH);
			if (!filePath.exists()) {
				filePath.mkdirs();
			}
			file.transferTo(new File(Constant.IMAGES_PATH + file.getOriginalFilename()));
			handover.setAnex(Constant.IMAGES_URL + "/" + file.getOriginalFilename());
		}
		if (iHandoverService.updateById(handover)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	@RequestMapping("/delete")
	@RequiresPermissions("/investment/handover/delete")
	@ResponseBody
	public Object delete(String[] id, HttpServletRequest request, HttpServletResponse response) {
		List list = new ArrayList<>();
		for (String string : id) {
			Handover handover = new Handover();
			handover.setId(string);
			handover.setDel(1);
			list.add(handover);
		}
		if (iHandoverService.updateBatchById(list)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 去审核
	 * 
	 * @param handover
	 * @param request
	 * @param response
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping("/toReview")
	@RequiresPermissions("/investment/handover/toReview")
	public String toReview(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		Handover handover = iHandoverService.selectById(id);
		String string = handover.getAreaCode();
		String[] strings = string.split(",");
		String province = strings[0];
		// 省
		Wrapper wrapper = Condition.create().like("id", "0000");
		List<Areas> provinces = iAreasService.selectList(wrapper);
		map.put("provinces", provinces);
		map.put("province", province);
		// 市
		String city = province.substring(0, 2);
		Wrapper cityWrapper = Condition.create().andNew("id like '" + city + "%00'").ne("id", city + "0000");
		List<Areas> citys = iAreasService.selectList(cityWrapper);
		map.put("citys", citys);
		map.put("city", strings[1]);
		// 区
		String county = strings[1].substring(0, 4);
		Wrapper countyWrapper = Condition.create().andNew("id like '" + county + "%'");
		List<Areas> countys = iAreasService.selectList(countyWrapper);
		map.put("countys", countys);
		map.put("county", strings[2]);

		List imidlist = iMerchantEmployeesService.selectEmployeesByRole("招商经理");
		List opidlist = iMerchantEmployeesService.selectEmployeesByRole("运营督导");
		List rgidlist = iMerchantEmployeesService.selectEmployeesByRole("区域经理");

		map.put("imidlist", imidlist);
		map.put("opidlist", opidlist);
		map.put("rgidlist", rgidlist);

		map.put("record", handover);
		return "investment/handover/review";
	}

	/**
	 * 审核
	 * 
	 * @param handover
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/review")
	@RequiresPermissions("/investment/handover/toReview")
	@ResponseBody
	public Object review(@Valid Handover handover, HttpServletRequest request, HttpServletResponse response) throws Exception {
		handover.setOperator(getUserId());
		handover.setRvid(getUserId());
		if (iHandoverService.updateState(handover)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 详情
	 * 
	 * @param handover
	 * @param request
	 * @param response
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping("/details")
	@RequiresPermissions("/investment/handover/details")
	public String details(String id, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		HandoverVo handover = iHandoverService.selectVoById(id);
		String string = handover.getAreaCode();
		String[] strings = string.split(",");
		String province = strings[0];
		// 省
		Wrapper wrapper = Condition.create().like("id", "0000");
		List<Areas> provinces = iAreasService.selectList(wrapper);
		map.put("provinces", provinces);
		map.put("province", province);
		// 市
		String city = province.substring(0, 2);
		Wrapper cityWrapper = Condition.create().andNew("id like '" + city + "%00'").ne("id", city + "0000");
		List<Areas> citys = iAreasService.selectList(cityWrapper);
		map.put("citys", citys);
		map.put("city", strings[1]);
		// 区
		String county = strings[1].substring(0, 4);
		Wrapper countyWrapper = Condition.create().andNew("id like '" + county + "%'");
		List<Areas> countys = iAreasService.selectList(countyWrapper);
		map.put("countys", countys);
		map.put("county", strings[2]);

		List imidlist = iMerchantEmployeesService.selectEmployeesByRole("招商经理");
		List opidlist = iMerchantEmployeesService.selectEmployeesByRole("运营督导");
		List rgidlist = iMerchantEmployeesService.selectEmployeesByRole("区域经理");

		map.put("imidlist", imidlist);
		map.put("opidlist", opidlist);
		map.put("rgidlist", rgidlist);

		Wrapper wrapper1 = Condition.create().eq("ifw.imid", handover.getImfid()).ne("ifw.del", 1);
		dwzPageBean.toPage().setSize(Page.NO_ROW_LIMIT);
		Page resultPage = iInvestmentFollowService.selectVoPage(dwzPageBean.toPage(), wrapper1);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));

		map.put("record", handover);
		return "investment/handover/detailsList";
	}

	/**
	 * 导出EXCEL
	 * 
	 * @param map
	 * @param dwzPageBean
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/export")
	@RequiresPermissions("/investment/handover/export")
	public String export(ModelMap map, DwzPageBean dwzPageBean, HttpServletRequest request, HttpServletResponse response) {
		// 从数据库中查找数据
		Wrapper wrapper = Condition.create().ne("h.del", 1);
		// 根据用户id获取角色
		// boolean isDirector = true;
		// List<Role> roles = getRoleList();
		// for (Role role : roles) {
		// if ("招商主管".equals(role.getName())) {
		// isDirector = false;
		// }
		// }
		// if (isDirector) {
		// wrapper.eq("maid", getUserId());
		// }
		Page page = dwzPageBean.toPage();
		page.setSize(Page.NO_ROW_LIMIT);
		page.setCurrent(1);
		List list = iHandoverService.selectVoPage(page, wrapper).getRecords();
		ExportParams params = new ExportParams(null, "客户信息", ExcelType.XSSF);
		IExcelDataHandler dataHandler = new MoneyExcelHandler();
		dataHandler.setNeedHandlerFields(new String[] { "报销费用", "管理费", "保证金", "店铺面积" });
		map.put(NormalExcelConstants.DATA_LIST, list); // 数据集合
		map.put(NormalExcelConstants.CLASS, HandoverVo.class);// 导出实体
		map.put(NormalExcelConstants.PARAMS, params);// 参数
		map.put(NormalExcelConstants.FILE_NAME, "客户信息");// 文件名称
		return NormalExcelConstants.EASYPOI_EXCEL_VIEW;// View名称
	}
}
